import os
import uuid

from flask import Blueprint

from config import UPLOAD_DIR
from model.user_resume import UserResume
from utils.securtiy import *
from utils.work_db import get_session
from service.user_resume_service import UserResumeService
from service.user_service import UserService
from service.company_service import CompanyService
from service.job_servie import JobService
from service.job_resume_service import JobResumeService
from service.user_deliver_service import UserDeliverStatusService
from model.user_deliver_status import UserDeliverStatus
from service.user_point_service import UserPointService
from model.user_point import UserPoint
from utils.work_log import get_logger

log = get_logger(__name__)
api = Blueprint('resume_api', __name__, url_prefix='/api/v1/resume')

"""
{
"user_id":"21",
"company_id":"1",
"job_id":"1"
}
"""
log = get_logger(__name__)


@api.route('/get', methods=['GET'])
@login_required
def get(**kwargs):
    """
    获得简历信息
    :param kwargs:
    :return:
    """
    session = get_session()
    q = session.query(UserResume)
    user_id = kwargs.get('user_id')
    q = q.filter(UserResume.user_id == user_id)
    result = q.first()
    if result:
        return jsonify({'data': {
            'user_id': result.user_id,
            'resume_id': result.resume_id,
            'mobile': result.mobile,
            'work_intention': result.work_intention,
            'work_history': result.work_history,
            'head_img': result.head_img,
            'age': result.age,
            'gender': result.gender,
            'real_name': result.real_name,
            'birth_day': result.birth_day if result.birth_day else '',
            'student_ok': result.student_ok if result.student_ok else '',
            'education': result.education
        }, 'code': 1})
    else:
        return jsonify({'data': {
        }, 'code': -1})


@api.route('/upload', methods=['POST'])
@login_required
def upload(**kwargs):
    """
    上传头像
    :param kwargs:
    :return:
    """
    head = request.files['head']
    suffix = head.filename.split('.')[-1]
    filename = str(uuid.uuid1()) + '.' + suffix
    head.save(os.path.join(UPLOAD_DIR, 'head', filename))
    user_id = kwargs.get('user_id')
    session = get_session()
    q = session.query(UserResume)
    q = q.filter(UserResume.user_id == user_id)
    result = q.first()
    if result is None:
        resume = UserResume()
        resume.user_id = user_id
        resume.head_img = filename
        resume.update_time = datetime.datetime.now()
        session.add(resume)
        session.commit()
    else:
        result.head_img = filename
        result.update_time = datetime.datetime.now()
        session.commit()
    return jsonify({'msg': '保存头像成功!', 'code': 1, 'data': {'head_img': filename}})


@api.route('/update', methods=['POST'])
@login_required
def update(**kwargs):
    """
    更新简历信息同时更新用户信息
    :param kwargs:
    :return:
    """
    args = request.json
    session = get_session()
    data = dict(args)
    resume = UserResume()
    resume.user_id = get_user_id()
    for k, v in data.items():
        setattr(resume, k, v)
    resume.update_time = datetime.datetime.now()
    if args.get("resume_id"):
        session.merge(resume)
    else:
        session.add(resume)
    session.commit()
    return jsonify({'msg': '保存成功', 'code': 1})


@api.route('/send', methods=['POST'])
@login_required
def send(**kwargs):
    """
    投递简历
    :param kwargs:
    :return:
    """
    user_id = get_user_id()
    params = request.json
    session = get_session()
    deliver_service = UserDeliverStatusService(session)
    resume_record = deliver_service. \
        get_send_records(user_id=int(user_id),
                         job_id=int(params.get("job_id"))
                         )
    if resume_record:
        return json_response(None, msg='该职位已经投递,不能重复投递!', code=-1)

    user_service = UserService(session)

    points_service = UserPointService(session)

    company_service = CompanyService(session)

    job_service = JobService(session)

    resume_service = UserResumeService(session)

    deliver_service = UserDeliverStatusService(session)

    user = user_service.get_by_id(user_id)
    company = company_service.get_by_company_id(int(params.get("company_id")))

    resume = resume_service.get_resume_by_user_id(user_id)
    job = job_service.get(int(params.get("job_id")))

    if not user:
        return json_response(None, msg='用户不存在!', code=-1)
    if not company:
        return json_response(None, msg='公司信息不存在!', code=-1)
    if not resume:
        return json_response(None, msg='简历信息不存在!', code=-1)
    if not job:
        return json_response(None, msg='职位信息不存在!', code=-1)

    # 只校验电话号码
    if not resume.mobile and not resume.tel:
        return json_response(None, msg='简历信息不完整!', code=-1)

    deliver = UserDeliverStatus()
    deliver.user_id = user.user_id
    deliver.resume_id = resume.resume_id
    deliver.job_id = job.job_id
    deliver.company_id = company.company_id
    deliver.deliver_date = datetime.datetime.now()
    deliver_service.send_resume(user_deliver=deliver)
    # 投递简历后待处理
    deliver.audit_status = 0
    points = UserPoint()
    points.user_id = user.user_id
    points.openid = user.openid
    points.points_code = 4
    points_service.add_points(points)

    session.commit()
    return json_response('', msg='投递成功', code=1)


@api.route('/list', methods=['POST'])
@login_required
def _list(**kwargs):
    """"""

    params = request.json
    read = None
    if not params or not params.get("user_id"):
        return json_response(None, msg='用户id不能为空!', code=-1)
    if params and params.get("read"):
        read = int(params.get("read", "0"))
    user_id = params.get("user_id")
    session = get_session()
    try:
        resume_service = JobResumeService(session)
        result = resume_service.list_resume_watch_record(read=read,
                                                         user_id=user_id)
        return json_response(result, msg='', code=1)
    except Exception as ex:
        log.error(str(ex))
    finally:
        session.close()


@api.route('/fast_send', methods=['POST'])
@login_required
def fast_send(**kwargs):
    """
    快速报名:对于没有简历的用户快速报名同时，生成简历，同时进行投递
    job_id
    :param kwargs:
    :return:
    """
    args = request.json
    job_id = args.get("job_id")
    session = get_session()
    deliver_service = UserDeliverStatusService(session)
    job_service = JobService(session)
    job = job_service.get(job_id=job_id)
    data = dict(args)
    resume = UserResume()
    resume.user_id = get_user_id()
    resume_service = UserResumeService(session)
    q_resume = resume_service.get_resume_by_user_id(user_id=get_user_id())
    if not q_resume:
        for k, v in data.items():
            setattr(resume, k, v)
        resume.update_time = datetime.datetime.now()
        session.add(resume)
        session.commit()
    else:

        resume = q_resume
    deliver = UserDeliverStatus()
    deliver.user_id = get_user_id()
    deliver.resume_id = resume.resume_id
    deliver.job_id = job_id
    deliver.company_id = job.company_id
    deliver.deliver_date = datetime.datetime.now()
    deliver_service.send_resume(user_deliver=deliver)
    # 投递简历后待处理
    deliver.audit_status = 0
    session.commit()
    session.close()
    return jsonify({'msg': '报名成功!', 'code': 1})
